<?php
declare(strict_types=1);

namespace Service\MemberService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Member;
use App\Model\BbcModel\MemberMessage;
use App\Model\BbcModel\Message;
use App\Model\BbcModel\MessageUserClick;
use App\Model\BbcModel\Mnuser;
/**
 * TO C/B SBBC消息中心
 * @author hj
 */
class MemberMessageService extends BaseService
{
    /**
     * 用户消息中心
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getInfo(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        $fields            = ['id', 'content', 'cd', 'is_read', 'type'];
        $allMsg            = MemberMessage::where('mid', $param['mid'])->where('df', 0)->select($fields)->orderBy('id', 'desc')->get();
        $notice            = $allMsg->where('type', 1)->first();
        $notice            = $notice ? $notice->toArray() : [];
        $notice['content'] = empty($notice) ? null : json_decode($notice['content'], true);
        $ship              = $allMsg->where('type', 2)->first();
        $ship              = $ship ? $ship->toArray() : [];
        $ship['content']   = empty($ship) ? null : json_decode($ship['content'], true);
        //老版本的 已经删除了
        // $active = \Ly\Model\SysMessage::instance()->info(['df'=>0,'type'=>3,'_order_'=>'id desc','_fields_'=>'id,content,cd']);
        $active            = [];
        $active['content'] = empty($active) ? null : json_decode($active['content'], true);
        return Normal::returnCode(Normal::SUC, '获取成功', ['notice' => $notice, 'ship' => $ship, 'custom' => null, 'active' => $active]);
    }

    /**
     * 消息列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getMessage(array $param)
    {
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $model = MemberMessage::where('df', 0);
        if (isset($param['mid']) && !empty($param['mid']) && (preg_match("/^[1-9]\d*$/", (string)$param['mid']) == 1)) {
            $model = $model->where('mid', $param['mid']);
        }
        if (isset($param['type']) && !empty($param['type'])) {
            $model = $model->where('type', $param['type']);
        }
        $fields = ['id', 'content', 'cd', 'is_read'];
        $result = $model->select($fields)->orderBy('id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        $result->each(function ($item, $key) {
            $content = json_decode($item->content, true);;
            $item->content = $content ? $content : [];
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', $result->items());
    }

    /**
     * 插入消息
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function insertMessage(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        $member = Member::where('mid', (int)($param['mid']))->exists();
        if (empty($member)) {
            return Normal::returnCode(Normal::FAIL, '用户不存在');
        }
        if (!isset($param['content']) || empty($param['content'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument content');
        }
        $title   = $param['title'] ?? '消息通知';
        $url     = $param['url'] ?? '';
        $content = [
            'title' => $title, 'content' => $param['content'], 'url' => $url
        ];
        $addData = [
            'content' => json_encode($content),
            'type'    => $param['type'] ?? 1,//1账户通知2交易物流,
            'mid'     => $param['mid'],
            'sid'     => getSID(),
            'cd'      => time(),
            'md'      => time(),
        ];
        $result  = MemberMessage::insert($addData);
        if (!$result) {
            return Normal::returnCode(Normal::FAIL, '新增失败');
        }
        return Normal::returnCode(Normal::SUC, '新增成功');
    }

    /**
     * 新系统消息列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function newGetMessage(array $param)
    {
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        if (isset($param['mnid']) && $param['mnid'] == 4) {
            $model = Message::where('df', 0)->where('type', 0)->where('status', 1);
            if (isset($param['cid']) && !empty($param['cid'])) {
                $model = $model->where('cid', $param['cid']);
            }
            $result = $model->select(['id', 'title', 'cd', 'description'])->orderBy('id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);
            if ($result->isEmpty()) {
                return Normal::returnCode(Normal::SUC, '获取成功');
            }
            $result->each(function ($item, $key) {
                $item->cd = date('Y-m-d', $item->cd);
                return $item;
            });
            return Normal::returnCode(Normal::SUC, '获取成功', $result->items());
        }
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['mn_sid']) || empty($param['mn_sid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mn_sid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mn_sid');
        }
        $check = Mnuser::validate($param);
        if ($check['code'] != Normal::SUC) {
            return $check;
        }
        $store      = $check['data'];
        $model      = Message::query()->from((new Message)->getTable() . ' as m')->leftJoin("ly_message_user_list as u", 'u.message_id', '=', 'm.id')
            ->where('m.type', 1)->where('m.df', 0)->where('m.status', 1)->where('m.cid', $param['cid'])->where('m.cd', '>=', $store['cd'])
            ->where(function ($query) use ($param) {
                $query->orWhere('u.target_id', 0)->orWhere('u.target_id', $param['mn_sid']);
            })->select(['m.id', 'm.title', 'm.cd', 'm.description', 'm.user_type']);
        $cloneModel = clone $model;
        $lists      = $model->orderBy('m.id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);;
        if ($lists->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功', ['no_read' => 0, 'list' => []]);
        }
        $collection      = $lists->getCollection();
        $msg_ids         = $collection->pluck('id')->toArray();
        $allMsgUserClick = MessageUserClick::whereIn('message_id', $msg_ids)->where('mid', $store['mid'])->where('cid', $param['cid'])->pluck('id', 'message_id')->toArray();
        $collection->each(function ($item, $key) use ($allMsgUserClick) {
            $item->cd      = date('Y-m-d H:i:s', $item->cd);
            $item->is_read = 0;
            $messageclick  = $allMsgUserClick[$item->id] ?? [];
            if ($messageclick) {
                $item->is_read = 1;
            }
            return $item;
        });
        $has    = 0;
        $allMsg = $cloneModel->get()->toArray();
        if ($allMsg) {
            $all_ids = array_column($allMsg, 'id');
            $has     = MessageUserClick::where('mid', $store['mid'])->where('cid', $param['cid'])->where('cd', '>=', $store['cd'])->whereIn('message_id', $all_ids)->count();
        }
        $no_read = round(count($allMsg) - $has);
        return Normal::returnCode(Normal::SUC, '获取成功', ['no_read' => $no_read, 'list' => $collection->toArray()]);
    }

    /**
     * 新系统消息详情
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function newGetDetail(array $param)
    {
        if (!isset($param['id']) || empty($param['id']) || (preg_match("/^[1-9]\d*$/", (string)$param['id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument id');
        }
        $info = Message::where('id', $param['id'])->where('df', 0)->first();
        if (!$info) {
            return Normal::returnCode(Normal::FAIL, '消息不存在');
        }
        if (isset($param['mid']) && !empty($param['mid']) && (preg_match("/^[1-9]\d*$/", (string)$param['mid']) == 1)) {
            $msgClick = MessageUserClick::where('message_id', $param['id'])->where('mid', $param['mid'])->where('cid', $info->cid)->exists();
            if (!$msgClick) {
                $info->click += 1;
                $info->save();
                MessageUserClick::insert(['message_id' => $param['id'], 'mid' => $param['mid'], 'cid' => $info['cid'], 'cd' => time(), 'sid' => getSID()]);
            }
            $info->total_click += 1;
            $info->group->save();
        }
        $info->cd = date('Y-m-d', $info->cd);
        return Normal::returnCode(Normal::SUC, '获取成功', $info->toArray());
    }

    /**
     * 获取首个信息
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getFirstMsg(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['mn_sid']) || empty($param['mn_sid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mn_sid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mn_sid');
        }
        $check = Mnuser::validate($param);
        if ($check['code'] != Normal::SUC) {
            return $check;
        }
        $store      = $check['data'];
        $model      = Message::query()->from((new Message)->getTable() . ' as m')->leftJoin("ly_message_user_list as u", 'u.message_id', '=', 'm.id')
            ->where('m.type', 1)->where('m.df', 0)->where('m.status', 1)->where('m.cid', $param['cid'])->where('m.cd', '>=', $store['cd'])
            ->where(function ($query) use ($param) {
                $query->orWhere('u.target_id', 0)->orWhere('u.target_id', $param['mn_sid']);
            })->select(['m.id', 'm.title', 'm.cd', 'm.description', 'm.user_type']);
        $cloneModel = clone $model;
        $info       = $model->orderBy('m.id', 'desc')->first();
        if (!$info) {
            return Normal::returnCode(Normal::SUC, '获取成功', ['no_read' => 0, 'title' => '']);
        }
        $has    = 0;
        $allMsg = $cloneModel->get()->toArray();
        if ($allMsg) {
            $all_ids = array_column($allMsg, 'id');
            $has     = MessageUserClick::where('mid', $store['mid'])->where('cid', $param['cid'])->where('cd', '>=', $store['cd'])->whereIn('message_id', $all_ids)->count();
        }
        $no_read = round(count($allMsg) - $has);
        return Normal::returnCode(Normal::SUC, '获取成功', ['no_read' => $no_read, 'title' => $info->title]);
    }
}